﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Xml;
using CabinetFile;
using EmbDocumentInhalatorSetup.ToolClasses;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.ComponentModel;
using System.Windows.Threading;
using System.Diagnostics;
using System.Data.Sql;
using System.Data.SqlClient;

namespace EmbDocumentInhalatorSetup
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
#region fieldsandproperties

        /// <summary>
        /// Holds all the features that belong to a specific solution
        /// </summary>
        private readonly FeatureCollection<Feature> _featureData =
            new FeatureCollection<Feature>();

        /// <summary>
        /// Hols all the solutions that are available.
        /// </summary>
        public SolutionCollection<Solution> LocatedSolutions =
            new SolutionCollection<Solution>();

        /// <summary>
        /// The current feature handled during the installer-action.
        /// </summary>
        Feature _currentFeature;

        /// <summary>
        /// The current solution handled during the installer action.
        /// </summary>
        private Solution _currentSolution;

        /// <summary>
        /// The web-apps handled during the installation.
        /// </summary>
        private Collection<SPWebApplication> collWebApps;

#endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindow"/> class.
        /// </summary>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:17
        public MainWindow()
        {
            _currentFeature = null;
            _currentSolution = null;
            InitializeComponent();
            
            CollapseRegions();

            // Insert code required on object creation below this point.
        }

        /// <summary>
        /// Collapses the regions.
        /// </summary>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:17
        private void CollapseRegions()
        {
            //InstallActions.Visibility = System.Windows.Visibility.Collapsed;
            lblSitesCaption.Visibility = Visibility.Collapsed;
            cmbSites.Visibility = Visibility.Collapsed;
            //Progress.Visibility = System.Windows.Visibility.Collapsed;
            prgInstallProgress.Visibility = Visibility.Collapsed;
            lblInstallStatus.Visibility = Visibility.Collapsed;
            lblSitesCaption.Visibility = System.Windows.Visibility.Hidden;
            cmbSites.Visibility = Visibility.Hidden;
        }

        /// <summary>
        /// Uns the collapse regions.
        /// </summary>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:17
        private void UnCollapseRegions()
        {
            InstallActions.Visibility = Visibility.Visible;
            lblSitesCaption.Visibility = Visibility.Visible;
            cmbSites.Visibility = Visibility.Visible;
            //Progress.Visibility = System.Windows.Visibility.Visible;
            prgInstallProgress.Visibility = Visibility.Visible;
            lblInstallStatus.Visibility = Visibility.Visible;
            lblSitesCaption.Visibility = Visibility.Visible;
            cmbSites.Visibility = Visibility.Visible;
        }



        /// <summary>
        /// Handles the Click event of the btnStartInstall control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:17
        private void btnStartInstall_Click(object sender, RoutedEventArgs e)
        {
            //Here we are in the pre-check phase
            //We check the access rights of the user
            if (((Button)sender).Content.ToString().Equals("_Pre-Check"))
            {
                ((Button)sender).IsEnabled = false;
                UpdateProgessStatus("Checking your SharePoint access rights...");

                if (CheckUserAccessRights())
                {
                    UpdateProgessStatus("You have sufficient rights to install.");

                    UpdateProgessStatus("Reading all WSPs...");

                    GetAllConfigFilesFromWsp();

                    UpdateProgessStatus("Finished reading WSPs...");

                    //Setting the data-context for the treeview
                    //TODO:CHANGE THE NAME HERE.
                    lstFeatures.DataContext = LocatedSolutions;
                    //TODO:CHANGE THE NAME HERE
                    lstInstallActions.DataContext = LocatedSolutions;

                    UpdateProgessStatus("Getting available sites on the server...");
                    //Fill the combobox with the data from the sites found on the server
                    FillSitesCombo();
                    //select the first entry in the combobox
                    cmbSites.SelectedIndex = 0;
                    //Now, start all the installation actions.
                    UpdateProgessStatus("Ready to perform install actions.");
                  
                    //Change the context in windows-forms style ....
                    ((Button)sender).Content = "_Next";
                    //...no comment....
                    ((Button)sender).IsEnabled = true;
                }
                else
                {
                    UpdateProgessStatus("You are not allowed to install solutions on this server.");
                    ((Button)sender).Content = "_Next";
                    ((Button)sender).IsEnabled = false;
                }
            }
            else if (((Button)sender).Content.ToString().Equals("_Next"))
            {
                //Show, what needs to be seen..
                UnCollapseRegions();

                InstallActions.Visibility = Visibility.Collapsed;

                InstallActionsChooseAction.Visibility = Visibility.Visible;
                
                ((Button)sender).Content = "_Go";
            }
            else if (((Button)sender).Content.ToString().Equals("_Go"))
            {
                UpdateProgessStatus("Performing install actions...");
                //Performing jobs using background worker
                BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork += new DoWorkEventHandler(worker_DoWork);
                worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

                cmbSites.IsEnabled = false;
                InstallActionsChooseAction.IsEnabled = false;

                ((Button)sender).IsEnabled = false;

                worker.RunWorkerAsync();


                
            }
        }

        /// <summary>
        /// Handles the RunWorkerCompleted event of the worker control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.RunWorkerCompletedEventArgs"/> instance containing the event data.</param>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:17
        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
          Dispatcher.Invoke(DispatcherPriority.Normal, 
                    new Action<string>(UpdateProgessStatus), 
                    ("Installation performed successfully.."));

          Dispatcher.Invoke(DispatcherPriority.Normal,
           new Action<bool>(UpdateProgressBarProperty),
           (false));

          MessageBox.Show("Installation performed successfully.");
          App.Current.Shutdown();

        }

        /// <summary>
        /// Handles the DoWork event of the worker control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.</param>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:17
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            Dispatcher.Invoke(DispatcherPriority.Normal,
                   new Action<string>(UpdateProgessStatus),
                   ("Installation is starting..."));
            Dispatcher.Invoke(DispatcherPriority.Normal,
                 new Action<bool>(UpdateProgressBarProperty),
                 (true));
           //Do all the important work.
            PerformInstallActions();
        }

        /// <summary>
        /// Updates the progress bar property.
        /// </summary>
        /// <param name="value">if set to <c>true</c> [value].</param>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:17
        private void UpdateProgressBarProperty(bool value)
        {
            prgInstallProgress.IsIndeterminate = value;

        }

        /// <summary>
        /// Updates the progess status.
        /// </summary>
        /// <param name="p">The p.</param>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:18
        private void UpdateProgessStatus(string p)
        {

            lblStatusText.Content = p;
            System.Threading.Thread.Sleep(2000);
        }

        /// <summary>
        /// Checks for update.
        /// </summary>
        /// <returns></returns>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:18
        private bool CheckForUpdate()
        {
            return false;
        }

        /// <summary>
        /// Updates the install options.
        /// </summary>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:18
        private void UpdateInstallOptions()
        {
        }

        /// <summary>
        /// Gets the solution I ds installed.
        /// </summary>
        /// <returns></returns>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:18
        private static List<string> GetSolutionIDsInstalled()
        {
            var ids = new List<string>();

            try
            {
                //TODO:PLEASE CHECK FOR SQLEXCEPTION
                SPFarm oFarm = SPFarm.Local;

                ids = SPFarm.Local.Solutions.Select(solution => solution.Id.ToString()).ToList();

                var sites = GetAllSitesOnFarm();

                foreach (var siteUrl in sites)
                {
                    using (var site = new SPSite(siteUrl))
                    {
                        ids.AddRange(from SPUserSolution s in site.Solutions select s.SolutionId.ToString());
                    }
                }

                
            }
            catch (SqlException sqlEx)
            {
                MessageBox.Show(sqlEx.Message + Environment.NewLine + "Please retry installation as Administrator.","SQL permission problem.");
                App.Current.Shutdown();

            }

            return ids;


        }

        /// <summary>
        /// Fills the sites combo.
        /// </summary>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:18
        private void FillSitesCombo()
        {
            var oFarm = SPFarm.Local;

            // Get all the services from the farm object
            foreach (var objService in oFarm.Services)
            {
                // Check if this is a WebService type of object
                if (!(objService is SPWebService)) continue;
                // Cast it to a WebService object
                var oWebService = (SPWebService)objService;

                // Get all Webapplications from the WebApplications collection
                foreach (var oWebApplication in oWebService.WebApplications)
                {
                    // Loop through all the sites
                    foreach (SPSite oSite in oWebApplication.Sites)
                    {
                        // Get reference of the Root object
                        var oWebRoot = oSite.RootWeb;
                        if (!(oWebRoot.Site.Url.Contains("Help") || oWebRoot.Site.Url.Contains("features")))
                        {
                            var item = new ComboBoxItem { Content = oWebRoot.Site.Url };

                            cmbSites.Items.Add(item);
                            // Any kind of processing
                        }
                        // Do not forget to dispose

                        oSite.Dispose();
                    }
                }
            }
        }




        /// <summary>
        /// Gets all sites on farm.
        /// </summary>
        /// <returns></returns>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:18
        private static IEnumerable<string> GetAllSitesOnFarm()
        {
            var sites = new List<string>();
            var oFarm = SPFarm.Local;

            // Get all the services from the farm object
            foreach (var objService in oFarm.Services)
            {
                // Check if this is a WebService type of object
                if (!(objService is SPWebService)) continue;
                // Cast it to a WebService object
                var oWebService = (SPWebService)objService;

                // Get all Webapplications from the WebApplications collection
                foreach (var oWebApplication in oWebService.WebApplications)
                {
                    // Loop through all the sites
                    foreach (SPSite oSite in oWebApplication.Sites)
                    {
                        // Get reference of the Root object
                        var oWebRoot = oSite.RootWeb;
                        //var item = new ComboBoxItem();
                        sites.Add(oWebRoot.Site.Url);

                        // Any kind of processing

                        // Do not forget to dispose

                        oSite.Dispose();
                    }
                }
            }

            return sites;
        }

        /// <summary>
        /// Checks the user access rights.
        /// </summary>
        /// <returns></returns>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:18
        private static bool CheckUserAccessRights()
        {
            return SPFarm.Local.CurrentUserIsAdministrator();
        }

        /// <summary>
        /// Gets all config files from WSP.
        /// </summary>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:18
        private void GetAllConfigFilesFromWsp()
        {
            //Get the path, and all the subfiles in WSPS-Folder.
            string currentPath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
            if (currentPath == null) return;
            string wspPath = new Uri(System.IO.Path.Combine(currentPath, "WSPS")).LocalPath;
            var solutionIdsOnServer = GetSolutionIDsInstalled();
            foreach (var file in System.IO.Directory.GetFiles(wspPath))
            {
                if (!System.IO.Path.GetExtension(System.IO.Path.GetFileName(file)).ToUpper().Equals(".WSP")) continue;
                string currentWSP = System.IO.Path.Combine(wspPath, file);
                var cabFile =
                    new TCabinetFile(currentWSP) { IgnoreInsidePath = true, OutputDirectory = wspPath };

                foreach (TFile currentFile in cabFile)
                {
                    //Get the solution data
                    if (currentFile.Name.ToUpper().Equals("MANIFEST.XML"))
                    {
                        _currentSolution = new Solution();
                        //MessageBox.Show(cabFile.Name + ":" +currentFile.FullName);
                        var doc = GetCurrentConfigXml(wspPath, cabFile, currentFile);

                        if (doc.DocumentElement != null)
                        {
                            _currentSolution.SolutionID = doc.DocumentElement.Attributes["SolutionId"].Value;
                        }

                        _currentSolution.IsInstalledOnServer = solutionIdsOnServer.Contains(_currentSolution.SolutionID);

                        if (doc.DocumentElement != null)
                            _currentSolution.IsSharpoint14Solution = doc.DocumentElement.HasAttribute("SharePointProductVersion") && doc.DocumentElement.Attributes["SharePointProductVersion"].Value.Equals("14.0");

                        //Add the current solution
                        if (_currentSolution.IsSharpoint14Solution)
                        {
                            _currentSolution.FullPathToWsp = file;
                            this.LocatedSolutions.Add(_currentSolution);
                        }
                    }

                    //Get the feature data
                    if (currentFile.Name.ToUpper().Equals("FEATURE.XML"))
                    {
                        _currentFeature = new Feature();
                        //Id="b1bda902-3f68-4553-9315-b120276115b8" Scope="Site"
                        //MessageBox.Show(cabFile.Name + ":" + currentFile.FullName);
                        var doc = GetCurrentConfigXml(wspPath, cabFile, currentFile);
                        if (doc.DocumentElement != null)
                        {
                            _currentFeature.FeatureID = doc.DocumentElement.Attributes["Id"].Value;
                            _currentFeature.FeatureTitle = doc.DocumentElement.Attributes["Title"].Value;
                            //currentFeature.CurrentVersion = doc.DocumentElement.Attributes["Version"].Value;

                            if (doc.DocumentElement.Attributes["Scope"].Value.ToUpper().Equals("FARM"))
                            {
                                _currentFeature.Scope = FeatureScope.Farm;
                            }
                            else if (doc.DocumentElement.Attributes["Scope"].Value.ToUpper().Equals("SITE"))
                            {
                                _currentFeature.Scope = FeatureScope.Site;
                            }
                        }

                        _featureData.Add(_currentFeature);
                    }
                }

                this._currentSolution.SolutionFeatures = new FeatureCollection<Feature>();

                foreach (var f in this._featureData)
                {
                    f.SolutionID = _currentSolution.SolutionID;
                    this._currentSolution.SolutionFeatures.Add(f);
                }

                this._featureData.Clear();
            }
        }

        /// <summary>
        /// Gets the current config XML.
        /// </summary>
        /// <param name="wspPath">The WSP path.</param>
        /// <param name="cabFile">The CAB file.</param>
        /// <param name="currentFile">The current file.</param>
        /// <returns></returns>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:18
        private static XmlDocument GetCurrentConfigXml(string wspPath, TCabinetFile cabFile, TFile currentFile)
        {
            cabFile.Extract(currentFile.FullName);

            var doc = new XmlDocument();
            doc.LoadXml(
                System.IO.File.ReadAllText(
                        wspPath + "\\" + currentFile.Name)
                        );

            string deleteFilePath = wspPath + "\\" + currentFile.Name;
            System.IO.File.Delete(deleteFilePath);

            return doc;
        }



        /// <summary>
        /// Checks the install options.
        /// </summary>
        /// <param name="box">The box.</param>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:19
        private void CheckInstallOptions(ComboBox box)
        {
            ComboBoxItem item = box.Items[0] as ComboBoxItem;

                //Get the solution.
                var s =
                    ((System.Windows.Controls.GridViewRowPresenter)
                     ((System.Windows.Controls.ContentPresenter)box.TemplatedParent).Parent).DataContext as Solution;

                var selectedItem = box.SelectedItem as ComboBoxItem;

                switch (selectedItem.Content.ToString())
                {
                    case "Update":
                        LocatedSolutions[LocatedSolutions.IndexOf(s)].InstallActionToPerform = InstallAction.Update;
                        break;
                    case "Repair"://TODO:IMPLEMENT, NOT USED.
                        LocatedSolutions[LocatedSolutions.IndexOf(s)].InstallActionToPerform = InstallAction.Repair;
                        break;
                    case "Remove":
                        LocatedSolutions[LocatedSolutions.IndexOf(s)].InstallActionToPerform = InstallAction.Uninstall;
                        break;
                    case "Install":
                        LocatedSolutions[LocatedSolutions.IndexOf(s)].InstallActionToPerform = InstallAction.Install;
                        break;
                    case "Ignore":
                        LocatedSolutions[LocatedSolutions.IndexOf(s)].InstallActionToPerform = InstallAction.Ignore;
                        break;
                }
           
           
        }

        /// <summary>
        /// Performs the install actions.
        /// </summary>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:19
        private void PerformInstallActions()
        {
            foreach (var solution in LocatedSolutions)
            {
                switch (solution.InstallActionToPerform)
                {
                    case InstallAction.Install:
                        InstallSolution(solution);
                        Dispatcher.Invoke(DispatcherPriority.Normal,
                    new Action<string>(UpdateProgessStatus),
                    ("Installing marked solutions...."));

                      
                        break;
                    case InstallAction.Update:
                        break;
                    case InstallAction.Repair:
                        break;
                    case InstallAction.Uninstall:
                        RemoveSolution(solution);
                        Dispatcher.Invoke(DispatcherPriority.Normal,
                                          new Action<string>(UpdateProgessStatus),
                                          ("Removing marked solutions...."));
                        break;
                    case InstallAction.Ignore:
                        break;
                }
            }
        }

        /// <summary>
        /// Delegate to return string values
        /// from controls from sepearate threads.
        /// </summary>
        delegate string GetItemString();

        /// <summary>
        /// Gets the combobox item caption.
        /// </summary>
        /// <returns></returns>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:19
        string GetComboboxItemCaption()
        {
            return ((ComboBoxItem)cmbSites.SelectedItem).Content.ToString();
        }

        /// <summary>
        /// Installs the solution.
        /// </summary>
        /// <param name="solutionToModify">The solution to modify.</param>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:19
        private void InstallSolution(Solution solutionToModify)
        {
            bool userSolutionInstalled = false;

            //Select the local farm for the installation process...
            SPFarm farm = SPFarm.Local;
            //Check if solution contains features to be installed in a site
            //if so, it is for 60% a Sandboxed thing.
            bool isUserSolution = false;

            foreach (Feature chf in solutionToModify.SolutionFeatures)
            {
                if (chf.Scope == FeatureScope.Site)
                    isUserSolution = true;
                Dispatcher.Invoke(DispatcherPriority.Normal,
                  new Action<string>(UpdateProgessStatus),
                  ("WSP contains user solutions."));
               
            }

            

            SPSolution sol = farm.Solutions.Add(solutionToModify.FullPathToWsp);


            Dispatcher.Invoke(DispatcherPriority.Normal,
                  new Action<string>(UpdateProgessStatus),
                  (String.Format("Installing Solution ID:{0}, in WSP:{1}",solutionToModify.SolutionID,
                System.IO.Path.GetFileName(solutionToModify.FullPathToWsp))));
            


            SPWebApplication application;
            string url = Dispatcher.Invoke(DispatcherPriority.Normal,
                  new GetItemString(GetComboboxItemCaption)) as string;
            application = SPWebApplication.Lookup(new Uri(url));

            this.collWebApps = new Collection<SPWebApplication> { application };
        

            if (this.collWebApps != null)
            {
                foreach (SPWebApplication app in collWebApps)
                {
                    if (app.ApplicationPool.Status == SPObjectStatus.Online)
                    {
                        bool stopIisApplicationPool =
                            IiisApplicationPoolManager.StopIisApplicationPool(app.ApplicationPool.Name);
                         Dispatcher.Invoke(DispatcherPriority.Normal,
                  new Action<string>(UpdateProgessStatus),
                  ("Stopping application pool..."));
                        
                    }
                }

                //Check if there are assemblies to be installed to gac
                if (sol.ContainsGlobalAssembly)
                {
                    sol.DeployLocal(true, collWebApps, true);
                    sol.Provision();
                     Dispatcher.Invoke(DispatcherPriority.Normal,
                  new Action<string>(UpdateProgessStatus),
                  ("Solution was deployed to GAC..."));
                   
                }
                else
                {
                    sol.DeployLocal(false, collWebApps, true);
                     Dispatcher.Invoke(DispatcherPriority.Normal,
                  new Action<string>(UpdateProgessStatus),
                  ("Solution was deployed to bin."));
                    sol.Provision();
                }

                foreach (Solution s in LocatedSolutions)
                {
                    if (s.SolutionID == sol.Id.ToString())
                    {
                        foreach (Feature f in s.SolutionFeatures)
                        {
                            if (f.Scope == FeatureScope.Site)
                            {
                                foreach (SPWebApplication webapp in collWebApps)
                                {
                                    foreach (SPSite site in webapp.Sites)
                                    {
                                        SPFeature installed = site.Features.Add(new Guid(f.FeatureID),
                                                                              true);
                                    }

                                    url = Dispatcher.Invoke(DispatcherPriority.Normal,
                                            new GetItemString(GetComboboxItemCaption)) as string;

                                    using (
                                        SPSite oSite =
                                            new SPSite(url)

                                        )
                                    {
                                        if (!userSolutionInstalled)
                                        {
                                            using (SPWeb oweb = oSite.OpenWeb())
                                            {
                                                SPWeb rootweb = oweb.Site.RootWeb;

                                                SaveWSPToLibrary(
                                            System.IO.File.ReadAllBytes(solutionToModify.FullPathToWsp)
                                            , System.IO.Path.GetFileName(solutionToModify.FullPathToWsp), ".wsp",
                                             "Solution Gallery", rootweb.Url);
                                                 Dispatcher.Invoke(DispatcherPriority.Normal,
                                                  new Action<string>(UpdateProgessStatus),
                                                  ("Uploading solution to site..."));
                                                 
                                                userSolutionInstalled = true;

                                                  Dispatcher.Invoke(DispatcherPriority.Normal,
                                                          new Action<string>(UpdateProgessStatus),
                                                          ("Activating user solution..."));
                                                //Activate the solution
                                                SPList solGallery = rootweb.Site.GetCatalog(SPListTemplateType.SolutionCatalog);
                                                foreach (SPListItem item in solGallery.Items)
                                                {
                                                    if (item.File.Name.Equals(System.IO.Path.GetFileName(solutionToModify.FullPathToWsp)))
                                                    {
                                                        SPUserSolution solutiontoActivate = rootweb.Site.Solutions.Add(item.ID);
                                                        EnsureSiteCollectionFeaturesActivated(solutiontoActivate, oSite); break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (f.Scope == FeatureScope.Farm)
                            {
                                SPFeature feature =
                                    SPWebService.AdministrationService.Features.Add(new Guid(f.FeatureID),
                                                                                    true);
                                 Dispatcher.Invoke(DispatcherPriority.Normal,
                                      new Action<string>(UpdateProgessStatus),
                                      ("Adding solution to farm..."));

                            }
                        }
                    }
                }

                foreach (SPWebApplication app in collWebApps)
                {
                    if (IiisApplicationPoolManager.CheckIisApplicationPoolStatus(app.ApplicationPool.Name) == 3)
                    {
                        bool stopIisApplicationPool =
                            IiisApplicationPoolManager.StartIisApplicationPool(app.ApplicationPool.Name);
                         Dispatcher.Invoke(DispatcherPriority.Normal,
                  new Action<string>(UpdateProgessStatus),
                  ("Restarting application pool..."));
                         
                    }
                }
            }
            else
            {
                //appPoolIds = SPSolutionDeploymentJobDefinition.StopWebServices();
            }

            Dispatcher.Invoke(DispatcherPriority.Normal,
                new Action<string>(UpdateProgessStatus),
                ("Solution installed successfully..."));
        }

        /// <summary>
        /// Ensures the site collection features activated.
        /// </summary>
        /// <param name="solution">The solution.</param>
        /// <param name="site">The site.</param>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:20
        static void EnsureSiteCollectionFeaturesActivated(SPUserSolution solution, SPSite site)
        {
            SPUserSolutionCollection solutions = site.Solutions;
            List<SPFeatureDefinition> oListofFeatures = GetFeatureDefinitionsInSolution(solution, site);
            foreach (SPFeatureDefinition def in oListofFeatures)
            {
                if (((def.Scope == SPFeatureScope.Site) && def.ActivateOnDefault) && (site.Features[def.Id] == null))
                {
                    site.Features.Add(def.Id, false, SPFeatureDefinitionScope.Site);
                }
            }
        }

        /// <summary>
        /// Gets the feature definitions in solution.
        /// </summary>
        /// <param name="solution">The solution.</param>
        /// <param name="site">The site.</param>
        /// <returns></returns>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:20
        static List<SPFeatureDefinition> GetFeatureDefinitionsInSolution(SPUserSolution solution, SPSite site)
        {
            List<SPFeatureDefinition> list = new List<SPFeatureDefinition>();
            foreach (SPFeatureDefinition definition in site.FeatureDefinitions)
            {
                if (definition.SolutionId.Equals(solution.SolutionId))
                {
                    list.Add(definition);
                }
            }
            return list;
        }

        /// <summary>
        /// Saves the WSP to library.
        /// </summary>
        /// <param name="wspData">The WSP data.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="fileExtension">The file extension.</param>
        /// <param name="listname">The listname.</param>
        /// <param name="url">The URL.</param>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:20
        private void SaveWSPToLibrary(byte[] wspData, string fileName, string fileExtension, string listname, string url)
        {

           string urlFromCombo = Dispatcher.Invoke(DispatcherPriority.Normal,
                                            new GetItemString(GetComboboxItemCaption)) as string;

            using (
                                           SPSite oSite =
                                               new SPSite(urlFromCombo)

                                           )
            {
                using (SPWeb oWebsite = oSite.OpenWeb())
                {
                    string folder = string.Empty;

                    if (oWebsite.Lists[listname] is SPDocumentLibrary)
                    {
                        folder = oWebsite.Lists[listname].RootFolder.Url;
                    }
                    else
                    {
                        folder = listname;
                    }

                    SPFileCollection oFiles = oWebsite.GetFolder(folder).Files;
                    string destUrl = SPEncode.UrlEncodeAsUrl(oFiles.Folder.ServerRelativeUrl) + "/" +
                        fileName;

                    SPFile oFileNew = oFiles.Add(destUrl, wspData, true);
                    SPListItem oListItem = oFileNew.Item;
                    oListItem.Properties.Add("Name", fileName);
                    oListItem.Update();
                }
            }
        }

        /// <summary>
        /// Removes the solution.
        /// </summary>
        /// <param name="solutionToModify">The feature to modify.</param>
        /// <returns></returns>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 06.02.2011,20:16
        private bool RemoveSolution(Solution solutionToModify)
        {
            var farmSol = GetFarmSolutionToModify(solutionToModify.SolutionID);

            if (farmSol == null)
            {
                var userSol = GetSiteolutionToModify(solutionToModify.SolutionID);
                if (userSol != null)
                {
                    var sites = GetAllSitesOnFarm();

                    foreach (var siteUrl in sites)
                    {
                        using (var site = new SPSite(siteUrl))
                        {
                            foreach (SPUserSolution us in site.Solutions)
                            {
                                if (us.SolutionId.ToString().Equals(userSol.SolutionId.ToString()))
                                {
                                    site.Solutions.Remove(us);
                                    using (SPWeb oweb = site.OpenWeb())
                                    {
                                        SPWeb rootWeb = oweb.Site.RootWeb;

                                        foreach (SPUserSolution solution in rootWeb.Site.Solutions)
                                        {
                                            if (solution.Name.Equals(System.IO.Path.GetFileName(solutionToModify.FullPathToWsp)))
                                            {
                                                rootWeb.Site.Solutions.Remove(solution);
                                                Dispatcher.Invoke(DispatcherPriority.Normal,
                                             new Action<string>(UpdateProgessStatus),
                                             ("Removing solution..."));
                                             
                                            }
                                        }
                                        // Code to Delete solution
                                        SPList solGallery1 = rootWeb.Site.GetCatalog(SPListTemplateType.SolutionCatalog);
                                        foreach (SPListItem item in solGallery1.Items)
                                        {
                                            if (item.File.Name.Equals(System.IO.Path.GetFileName(solutionToModify.FullPathToWsp)))
                                            {
                                                solGallery1.Items.DeleteItemById(item.ID);
                                                Dispatcher.Invoke(DispatcherPriority.Normal,
                                                 new Action<string>(UpdateProgessStatus),
                                                 ("Removing user solution..."));
                                                
                                                break;
                                            }
                                        }
                                    }
                                    foreach (SPFeature f in site.Features)
                                    {
                                        foreach (Feature fi in solutionToModify.SolutionFeatures)
                                        {
                                            if (f.DefinitionId.ToString().Equals(fi.FeatureID))
                                            {
                                                site.Features.Remove(f.DefinitionId);
                                                Dispatcher.Invoke(DispatcherPriority.Normal,
                                                   new Action<string>(UpdateProgessStatus),
                                                   ("Removing solution features..."));
                                            }
                                        }
                                    }
                                }

                                return true;
                            }
                        }
                    }
                }
            }
            else
            {
                SPFarm.Local.Solutions[farmSol.Id].Delete();
                Dispatcher.Invoke(DispatcherPriority.Normal,
                 new Action<string>(UpdateProgessStatus),
                 ("Farm solution deleted..."));

                return true;
            }

            return false;
        }

        /// <summary>
        /// Gets the farm solution to modify.
        /// </summary>
        /// <param name="solutionId">The solution id.</param>
        /// <returns></returns>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 06.02.2011,21:38
        private static SPSolution GetFarmSolutionToModify(string solutionId)
        {
            //TODO:PLEASE CHECK FOR SQLEXCEPTION
            SPFarm oFarm = SPFarm.Local;

            var ids = SPFarm.Local.Solutions.Select(solution => solution.Id.ToString()).ToList();

            if (ids.Contains(solutionId))
            {
                var solutionToModify = from
                                       solution in SPFarm.Local.Solutions
                                       where solution.Id.ToString().Equals(solutionId)
                                       select solution;

                return solutionToModify.First();
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// Gets the siteolution to modify.
        /// </summary>
        /// <param name="solutionId">The solution id.</param>
        /// <returns></returns>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 06.02.2011,21:38
        private static SPUserSolution GetSiteolutionToModify(string solutionId)
        {
            var sites = GetAllSitesOnFarm();

            foreach (var siteUrl in sites)
            {
                using (var site = new SPSite(siteUrl))
                {
                    foreach (SPUserSolution s in site.Solutions)
                    {
                        if (s.SolutionId.ToString().Equals(solutionId))
                        {
                            return s;
                        }
                    }
                }
            }

            return null;
        }
       
#region notused

        private bool UdpateSolution()
        {
            throw new NotImplementedException();
        }

        private bool RepairSolution()
        {
            throw new NotImplementedException();
        }

        private bool InstallSolution()
        {
            throw new NotImplementedException();
        }
#endregion


        /// <summary>
        /// Handles the SelectionChanged event of the cmbNotInstalledOnServer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Controls.SelectionChangedEventArgs"/> instance containing the event data.</param>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:21
        private void cmbNotInstalledOnServer_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox b = (ComboBox)sender;
            CheckInstallOptions(b);
        }

        /// <summary>
        /// Handles the Loaded event of the cmbNotInstalledOnServer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 12.02.2011,22:21
        private void cmbNotInstalledOnServer_Loaded(object sender, RoutedEventArgs e)
        {
            ComboBox b = (ComboBox)sender;
            CheckInstallOptions(b);
        }

        /// <summary>
        /// Handles the RequestNavigate event of the Hyperlink control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Navigation.RequestNavigateEventArgs"/> instance containing the event data.</param>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 13.02.2011,00:04
        private void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
        {
            Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));

            e.Handled = true;

        }

      
    }
}